<template>
  <div class="contain-total">

    <el-container style="display: flex; flex-direction: column; align-items: center">
      <div class="container-box">
        <div>
          <div class="echarts-container">
            <div class="over">
              <el-statistic title="已完成" :value="overTaskNum"/>
            </div>
            <div class="not-over">
              <el-statistic title="未完成" :value="notOverTaskNum"/>
            </div>
            <div id="echarts-contain">

            </div>
          </div>
          <el-divider border-style="solid"/>
          <div>
            <div class="gantt-top-container">
              <div class="search">
                <span>请输入任务标题：</span>
                <el-input placeholder="请输入任务标题" style="width: 200px" v-model="taskName" clearable>

                </el-input>
                <el-button style="margin-left: 20px" type="primary" @click="getGanttData">搜索</el-button>
              </div>
              <div class="excel-contain">
                <el-button @click="exportData" style="height: 40px">导出excel</el-button>
              </div>
            </div>
            <section class="my-gantt">
              <div id="gantt_here" class="gantt-container"></div>
            </section>
          </div>
        </div>

      </div>
    </el-container>
  </div>


</template>

<script setup>
import {
  reactive,
  onBeforeMount,
  onMounted,
  defineExpose,
  ref,
  nextTick, computed
} from 'vue'

import {gantt} from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import {getGantt, getGanttProject} from "@/api/task/task.js"
import {ElMessage} from "element-plus";
import {useRoute, useRouter} from "vue-router";
import { useTransition } from '@vueuse/core'
const router = useRouter()
const route = useRoute()

const data = reactive({})
const taskName = ref("")
const overTaskNum = ref(0)
const notOverTaskNum = ref(0)


/**
 * animateValue - 动画过渡数字
 * @param {Ref<number>} refValue - 需要动画更新的响应式引用
 * @param {number} target - 目标值
 * @param {number} duration - 动画持续时间（毫秒）
 */
function animateValue(refValue, target, duration = 2000) {
  const startValue = refValue.value;
  const change = target - startValue;
  const startTime = performance.now();

  function updateValue(currentTime) {
    const elapsed = currentTime - startTime;
    // 计算当前进度（0～1）
    const progress = Math.min(elapsed / duration, 1);
    // 计算当前的值
    refValue.value = startValue + change * progress;
    // 如果还未完成，继续动画
    if (progress < 1) {
      requestAnimationFrame(updateValue);
    }
  }

  requestAnimationFrame(updateValue);
}



import * as echarts from 'echarts';


const setEcharts = () => {
  nextTick(() => {
    const chartDom = document.getElementById('echarts-contain');
    const myChart = echarts.init(chartDom);
    let option;

    option = {
      title: {
        text: '完成比例图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      color: ['#75e375', '#e55555'], // 颜色顺序，第一个数据项是绿色，第二个是红色
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: [
            {value: overTaskNum.value, name: '已完成'},
            {value: notOverTaskNum.value, name: '未完成'}// 设定 "未完成" 颜色}
          ],
          label: {
            show: false // 隐藏标签
          },
          labelLine: {
            show: false // 确保指示线不显示
          },
          emphasis: {
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    option && myChart.setOption(option);
  })
}


function exportData() {
  gantt.exportToExcel({
    visual: true
  })
}

const ganttDate = ref({
  data: []
})
const zoomConfig = {
  levels: [
    [
      {unit: "year", step: 1, format: "%Y"}, // 按年显示
      {unit: "month", step: 1, format: "%M"} // 按月份显示
    ],
    [
      {unit: "month", step: 1, format: "%Y-%m"}, // 按月显示
      {unit: "day", step: 3, format: "%d 日"}
    ],
    [
      {unit: "month", step: 1, format: "%Y-%m"}, // 按月显示
      {unit: "day", step: 1, format: "%d 日"}
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {unit: "hour", format: "%H:%i", step: 5}
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "hour", format: "%H:%i", step: 1
      }
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "minute", format: "%H:%i", step: 30
      }
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "minute", format: "%H:%i", step: 15
      }
    ],
  ],
  useKey: "ctrlKey",
  trigger: "wheel",
  element: function () {
    return gantt.$root.querySelector(".gantt_task");
  }

}

onBeforeMount(async () => {
  await getGanttData()
})

const getGanttData = async () => {
  animateValue(0, overTaskNum.value, 1000);
  animateValue(0, notOverTaskNum.value, 1000);
  const res = await getGantt({
    "taskName": taskName.value,
    "projectId": route.query.id,
    "isProject": 1
  })
  const res2 = await getGanttProject({
    "taskName": taskName.value,
    "projectId": route.query.id
  })
  if (res.data.code === 200 && res2.data.code === 200) {
    ElMessage.success('获取数据成功')
    let data = [...res.data.result]
    const data2 = [...res2.data.result]
    overTaskNum.value = 0
    notOverTaskNum.value = 0
    setEcharts()
    data2.forEach(item => {
      item.text = item.projectName
      item.progress = 0
      item.start_date = item.projectStartTime
      item.taskStartTime = item.projectStartTime
      item.end_date = item.projectEndTime
      item.taskEndTime = item.projectEndTime
      item.open = true
      item.userNamesString = "-"
      item.state = "-"
    })

    data = data.filter(item => {
      item.text = item.taskName
      item.progress = item.process * 0.01
      item.state = item.process + ""
      item.parent = item.projectId
      item.open = true
      if (item.taskStartTime && item.taskEndTime) {
        if (item.progress !== 1) {
          notOverTaskNum.value++;
        } else {
          overTaskNum.value++;
        }
        item.start_date = item.taskStartTime;
        item.end_date = item.taskEndTime;
        return true; // 保留该项
      }
      return false; // 过滤掉不符合条件的项
    })
    ganttDate.value.data = [...data, ...data2]
    gantt.clearAll()
    gantt.addMarker({
      start_date: new Date(), // 在当前时间戳添加标记
      css: "today",
      text: "当前时间",
      title: "当前时间"
    });
    gantt.parse(ganttDate.value)   //填充数据
  } else {
    ElMessage.error('获取数据失败')
  }
}
//初始化甘特图
const initGantt = () => {
  gantt.config.grid_width = 350
  gantt.config.add_column = false //添加符号
  gantt.config.scale_height = 60;
  gantt.config.fit_tasks = false; // 关闭自动调整任务时间
  gantt.config.autofit = false; // 关闭自动填充

  gantt.config.columns = [
    {name: 'text', label: '项目名称', tree: true, width: '100', align: 'center'},
    {name: 'state', label: '任务进度（%）', width: '100', align: 'center'},
    {name: 'userNamesString', label: '任务成员', width: '100', align: 'center'},
    {name: 'taskStartTime', label: '任务/项目开始时间', width: '150', align: 'center'},
    {name: 'taskEndTime', label: '任务/项目结束时间', width: '150', align: 'center'},

  ]

  gantt.templates.tooltip_text = (start, end, task) => {
    let tooltips = [];
    tooltips.push("任务名称: " + task.text);
    if (task.parent !== 0){
      tooltips.push(`进度: ${
          task.state === "100"
              ? `<span style="color:green">${task.state}%</span>`
              : `<span style="color:#e74c3c">${task.state}%</span>`
      }`);
      tooltips.push("任务成员: " + task.userNamesString);
    }
    tooltips.push("开始时间: " + task.taskStartTime);
    tooltips.push("结束时间: " + task.taskEndTime);
    return `<div>
        ${tooltips.join('<br>')}
    </div>`;
  }
  gantt.templates.progress_text = (start, end, task) => {
    if (task.parent !== 0 && task.state !== 100){
      return task.state + "%"
    }
  }
// task 自定义样式
  gantt.templates.task_class = function (start, end, task) {
    if (task.parent === 0){
      return "project_timeline"
    }
  };
  gantt.config.autofit = false
  gantt.config.row_height = 60
  gantt.config.bar_height = 34
  gantt.config.auto_types = true //将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
  gantt.config.readonly = true //是否只读
  gantt.i18n.setLocale('cn') //设置语言
  gantt.templates.parse_date = function (dateString) {
    return new Date(dateString);
  };

  gantt.templates.format_date = function (date) {
    return date.toISOString();
  };

  gantt.plugins({
    export_api: true,
    marker: true, tooltip: true, zoom: true
  });


  gantt.init('gantt_here')  //初始化
  gantt.addMarker({
    start_date: new Date(), // 在当前时间戳添加标记
    css: "today",
    text: "当前时间",
    title: "当前时间"
  });
  gantt.parse(ganttDate.value)   //填充数据
  gantt.ext.zoom.init(zoomConfig);

}

onMounted(() => {
  initGantt()
})
defineExpose({
  getGanttData
})

</script>
<style scoped>
.my-gantt {
  height: 600px;
  margin-top: 20px;

  .gantt-container {
    width: 100%;
    height: 100%;
  }
}

.echarts-container {
  height: 320px;
  padding: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-items: center;
  justify-content: space-between;
}

.over {
  width: 150px;
  height: 150px;
  background-color: #9d9dd6;
  border-radius: 80px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
:deep(.gantt_tooltip){
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  color: #333;
  font-size: 14px;
  /* 可根据需要添加其他样式 */
}

.not-over {
  width: 150px;
  height: 150px;
  background-color: #e55555;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

#echarts-contain {
  width: 300px;
  height: 300px;
}

.contain-total {
  background-color: white;
  padding: 20px;
}

.search {
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
}

.gantt-top-container {
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
  position: relative;
}

.excel-contain {
  position: absolute;
  right: 0;
}

.container-box {
  width: 100%;
}

.container-box {
  display: flex;
  flex-direction: column;
  background-color: white;
  padding: 0 20px;
}

/* 针对左侧表格头部 */
:deep(.gantt_grid_scale) {
  height: 60px !important; /* 调整表头整体高度 */
  line-height: 60px !important; /* 文字垂直居中 */
}
:deep(.project_timeline) {
  background: rgba(87, 85, 85, 0.9);
}
:deep(.el-statistic) {
  display: flex;
  align-items: center;
  flex-direction: column;
}
</style>
